/**
 * 
 */

package com.trydofor.id.mess;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

import com.trydofor.id.core.A9Loader;
import com.trydofor.id.core.ApiExceptions;

/**
 * @author : Shi Rongjiu (www.trydofor.com)
 */
public class LazyEntryLoader implements A9Loader<List<Integer>>{
    
    private final AtomicInteger uniqueCq = new AtomicInteger();
    private final AtomicBoolean loadExcp = new AtomicBoolean(false);
    private final AtomicBoolean dealExcp = new AtomicBoolean(false);
    private final AtomicBoolean slowLoad = new AtomicBoolean(false);
    private final int           load;
    
    public LazyEntryLoader(int first, int load) {
        this.load = load;
        uniqueCq.set(first);
    }
    
    @Override
    public List<Integer> heavyLoad() throws Exception {
        if (slowLoad.get()) Thread.sleep(100);
        final int cq = uniqueCq.getAndIncrement();
        if (loadExcp.get()) throw new Exception("throw an Exception when cq=" + cq);
        List<Integer> r = new ArrayList<Integer>(load);
        r.add(Integer.valueOf(cq));
        for (int i = 1; i < load; i++) {
            r.add(Integer.valueOf(uniqueCq.getAndIncrement()));
        }
        return r;
    }
    
    @Override
    public void handleException(Exception e) {
        final boolean ex = dealExcp.get();
        if (ex) {
            ApiExceptions.throwFakeException(e);
        }
    }
    
    public void setThrowOnLoad(boolean b) {
        loadExcp.set(b);
    }
    
    public void setThrowOnHandle(boolean b) {
        dealExcp.set(b);
    }
    
    public void setSlowLoad(boolean b) {
        slowLoad.set(b);
    }
}
